/**
 * 登录接口
 */

// 查询登录接口
import pool from "@/lib/db";
import { FieldPacket } from "mysql2";
import { NextResponse } from "next/server";

interface ILoginRequest {
    id: React.Key;
  name: string;
  age: number;
  password: string;
  deparetmentId: React.Key;
}

export async function POST(request: Request) {
  const { username, password } = await request.json();
  try {
  const connection = await pool.getConnection();
    // 执行 MySQL 查询
    const [rows, fields] = await connection.query('SELECT * FROM user WHERE name = ?', [username]) as [ILoginRequest[], FieldPacket[]];
    // 释放连接回连接池 as [ILoginRequest[], any]
    connection.release()
    if (rows.length > 0) {
      // 验证密码
      if (rows[0].password === password) {

        return NextResponse.json({ code: 200, msg: '登录成功' },{
          headers: { 'Set-Cookie': `token=${rows[0].id}; Path=/; HttpOnly` },
        })
      } else {
        return NextResponse.json({ code: 401, msg: '密码错误' }, { status: 200 })
      }
    } else {
      return NextResponse.json({ code: 404, msg: '用户不存在' }, { status: 200 })
    }
  } catch (error) {
    console.error('Error:', error)
    return NextResponse.json({ code: 500, msg: 'Internal Server Error' }, { status: 500 })
  }


    // 简单的用户名和密码验证逻辑
}